<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './lessonTableData';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { lessonSaveApi, lessonUpdateApi } from '/@/api/resource/lessonApi';

  const isUpdate = ref(true);

  const id = ref(0);

  const parentCourseId = ref(0);

  const emit = defineEmits(['success']);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas: formSchema,

    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    console.log(data);
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    id.value = data?.data?.id;
    parentCourseId.value = data?.data?.parentCourseId;
    console.log(parentCourseId.value);
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.data,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const values = await validate();
      values.id = id.value;
      console.log(parentCourseId.value);
      values.parentCourseId= parentCourseId.value;
      setDrawerProps({ confirmLoading: true });

      await (!unref(isUpdate) ? lessonSaveApi(values) : lessonUpdateApi(values));
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
